﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HHMMS.WorkFlow;
using HHMMS.Core.Service;
using Bingosoft.Web.Utils;
using HHMMS.Core.Model;

namespace HHMMS.UI.Modules.Workflow.Forms
{
    public partial class PurchasePlan : WFUserControl
    {
        private readonly PurchasePlanDocService _purchasePlanDocService = ObjectHelper.GetObject<PurchasePlanDocService>();
        private readonly PurchaseSuppliesPlanService suppliesService = ObjectHelper.GetObject<PurchaseSuppliesPlanService>(); 

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.ActionType > 0)
            {
                var purchasePlanDoc = _purchasePlanDocService.GetPurchasePlanDoc(this.DataKey.ConvertTo<int>());
                if (purchasePlanDoc != null)
                {
                    SmartForm.Fill(this, purchasePlanDoc);
                }
            }
        }

        public override bool SaveData()
        {
            var purchasePlanDoc = SmartForm.GetEntity<PurchasePlanDoc>(this);

            _purchasePlanDocService.SaveOrUpdatePurchasePlanDoc(purchasePlanDoc);

            this.Title = purchasePlanDoc.Title;
            this.DataKey = purchasePlanDoc.DocId + "";

            return base.SaveData();
        }

        public override void OnWorkflowExecute(object sender, WorkflowEventArgs e)
        {
            base.OnWorkflowExecute(sender, e);

            var purchasePlanDoc = _purchasePlanDocService.GetPurchasePlanDoc(this.DataKey.ConvertTo<int>());
            if (purchasePlanDoc != null)
            {
                purchasePlanDoc.WFInstanceId = e.Instance.InstanceId;
                purchasePlanDoc.Status = e.Instance.InstanceStatus + 1;
                if (e.Instance.InstanceStatus == 2)
                {
                    purchasePlanDoc.PassTime = DateTime.Now;
                }
                _purchasePlanDocService.SaveOrUpdatePurchasePlanDoc(purchasePlanDoc);
            }
        }

        protected void SearchGrid(object sender, EventArgs e)
        {
            this.gridParts.DataBind();
        }

        protected void RefreshGrid(object sender, EventArgs e)
        {
            this.gridParts.DataBind();
        }

        protected void DeletePurchaseSuppliesPlan(object sender, EventArgs e)
        {
            ImageButton ctr = sender as ImageButton;
            int docId = ctr.Attributes["_ID"].ConvertTo<int>();
            string partName = ctr.Attributes["_PartName"];
            string partMedel = ctr.Attributes["_PartModel"];

            this.suppliesService.DeletePurchaseSuppliesPlan(docId, partName, partMedel);

            this.gridParts.DataBind();
        }
    }
}